package com.newgrand.annexserver.listener;

import com.newgrand.annexcommon.constant.DBUserTypeConstants;
import com.newgrand.annexcommon.constant.StatusConst;
import com.newgrand.annexcommon.constant.StoreStrateType;
import com.newgrand.annexcommon.model.DbConfigEnity;
import com.newgrand.annexserver.beans.Dbconfig;
import com.newgrand.annexserver.datasource.NgDynamicDataSourceBeanRegistry;
import com.newgrand.annexserver.service.DbconfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ：minyang
 * @date ：Created in 2019/9/8 9:47
 */
@Component
public class DbSourceListener implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger logger = LoggerFactory.getLogger(DbSourceListener.class);

    @Autowired
    DbconfigService dbconfigService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            //注册数据源
            List<Dbconfig> dbconfigList = dbconfigService.getDBConfigList(StatusConst.STATE_ENALBE);
            dbconfigList.forEach(dbconfig -> {
                //注册数据源
                DbConfigEnity enity1 = new DbConfigEnity();
                enity1.setDbtoken(dbconfig.getDbtoken());
                enity1.setdBUserType(DBUserTypeConstants.business_type);
                enity1.setDriverClassName(dbconfig.getDriverClassName());
                enity1.setUrl(dbconfig.getUrl());
                enity1.setPassword(dbconfig.getPassword());
                enity1.setUsername(dbconfig.getUsername());
                NgDynamicDataSourceBeanRegistry.updateDynamicDataSource(enity1);
                if (dbconfig.getStoreStratetype() == StoreStrateType.mysql || dbconfig.getStoreStratetype() == StoreStrateType.oracle
                        || dbconfig.getStoreStratetype() == StoreStrateType.sqlserver) {
                    //注册存储数据源
                    DbConfigEnity enity2 = new DbConfigEnity();
                    enity2.setDbtoken(dbconfig.getDbtoken());
                    enity2.setdBUserType(DBUserTypeConstants.store_type);
                    enity2.setDriverClassName(dbconfig.getStoreDriverClassName());
                    enity2.setUrl(dbconfig.getStoreUrl());
                    enity2.setPassword(dbconfig.getStorePassword());
                    enity2.setUsername(dbconfig.getStoreUsername());
                    NgDynamicDataSourceBeanRegistry.updateDynamicDataSource(enity2);
                }

            });
            //todo 加入redis缓存

        }
    }
}
